{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "<a href=\"https://colab.research.google.com/drive/1KKqbrAFnYkNyYjqlDGiRJankXBuBk2tI?usp=sharing\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n",
        "\n",
        "\n",
        "### 🤔 ReACT (Reasoning and Acting) - Prompt Engineering\n",
        "\n",
        "ReAct is an advanced prompting method that combines reasoning and acting in language models.\n",
        "\n",
        "### Key points\n",
        "\n",
        "* 🔑 **Core concept:** Interleaves thought generation with action execution.\n",
        "\n",
        "* 🛠️ **Components:** Thought, Action, Observation cycle.\n",
        "\n",
        "* ⚙️ **Process:**\n",
        "  * **Thought:** Model reasons about the current state\n",
        "  * **Action:** Decides on and executes an action\n",
        "  * **Observation:** Receives feedback from the environment\n",
        "\n",
        "* 💼 **Applications:** Task-solving, information retrieval, decision-making.\n",
        "\n",
        "* 🌟 **Advantages:**\n",
        "  * Improves problem-solving abilities\n",
        "  * Enhances model's interaction with external tools/data\n",
        "\n",
        "* 🚀 **Implementation:** Uses specific prompts to guide the model through the Thought-Action-Observation cycle.\n",
        "\n",
        "* 📝 **Example structure:**\n",
        "  * **Thought:** [Reasoning about the task]\n",
        "  * **Action:** [Chosen action, e.g., 'Search for X']\n",
        "  * **Observation:** [Result of the action]\n",
        "  * **Thought:** [Next step based on observation]\n",
        "\n",
        "* 📈 **Use cases:** Web navigation, complex multi-step tasks, interactive problem-solving."
      ],
      "metadata": {
        "id": "Y2eqHW0TK87s"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install -q -U langchain-groq==0.2.4"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "KI4D1HL-LKaP",
        "outputId": "63436823-1137-4603-8388-cecc280d4a42"
      },
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\u001b[?25l   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/121.9 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m121.9/121.9 kB\u001b[0m \u001b[31m6.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain_groq import ChatGroq\n",
        "from langchain.prompts import ChatPromptTemplate"
      ],
      "metadata": {
        "id": "dfHHptAFLMwj"
      },
      "execution_count": 2,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "import getpass"
      ],
      "metadata": {
        "id": "eZJGDTIMLOnP"
      },
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 🔑 Provide Groq API Key\n",
        "\n",
        "- [Groq API Key](https://console.groq.com/keys)\n",
        "\n"
      ],
      "metadata": {
        "id": "rQrlkg_bLRZp"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "os.environ[\"GROQ_API_KEY\"] = getpass.getpass()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "XI8sLK8uLTht",
        "outputId": "f8eaa8b5-5a81-4b86-943a-e48d16ffae26"
      },
      "execution_count": 4,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "··········\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "llm = ChatGroq(\n",
        "    model=\"llama3-8b-8192\",\n",
        "    temperature=0.5\n",
        ")"
      ],
      "metadata": {
        "id": "0os_AIehLVh1"
      },
      "execution_count": 5,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "react_prompt = ChatPromptTemplate.from_messages(\n",
        "    [\n",
        "        (\"system\", \"You are an AI assistant capable of reasoning and acting. Approach tasks step-by-step, explaining your thought process and actions.\"),\n",
        "        (\"human\", \"\"\"Task: {task}\n",
        "\n",
        "          Think through this task step by step:\n",
        "          1) Analyze the task and identify key components\n",
        "          2) Determine what information or actions are needed\n",
        "          3) If information is needed, state what you need to know\n",
        "          4) If an action is needed, describe the action\n",
        "          5) Repeat steps 3-4 until the task is complete\n",
        "          6) Provide the final answer or solution\n",
        "\n",
        "          Your response:\"\"\"),\n",
        "    ]\n",
        ")\n",
        "\n",
        "chain = react_prompt | llm"
      ],
      "metadata": {
        "id": "FToKQB7jLBYD"
      },
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "task =  \"Calculate the total cost of a shopping trip where you buy 3 apples at $0.50 each and 2 loaves of bread at $2.25 each. Don't forget to add 8% sales tax.\"\n",
        "response = chain.invoke({\"task\": task})\n",
        "print(response.content)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "0PWEvnMyLZSb",
        "outputId": "088a13ac-b0ff-4e4a-f91a-356ccb91f4b8"
      },
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "I'd be happy to walk you through the task step-by-step.\n",
            "\n",
            "**Step 1: Analyze the task and identify key components**\n",
            "\n",
            "The task is to calculate the total cost of a shopping trip. The components of the task are:\n",
            "\n",
            "* Items purchased: 3 apples and 2 loaves of bread\n",
            "* Prices: $0.50 per apple and $2.25 per loaf of bread\n",
            "* Sales tax: 8%\n",
            "\n",
            "**Step 2: Determine what information or actions are needed**\n",
            "\n",
            "To complete the task, I need to:\n",
            "\n",
            "* Calculate the total cost of the apples\n",
            "* Calculate the total cost of the bread\n",
            "* Calculate the total cost including sales tax\n",
            "\n",
            "**Step 3: State what I need to know**\n",
            "\n",
            "I need to know the prices of the items and the number of items purchased.\n",
            "\n",
            "**Step 4: Describe the action**\n",
            "\n",
            "To calculate the total cost of the apples, I will multiply the number of apples by the price per apple:\n",
            "\n",
            "3 apples x $0.50 per apple = $1.50\n",
            "\n",
            "To calculate the total cost of the bread, I will multiply the number of loaves by the price per loaf:\n",
            "\n",
            "2 loaves x $2.25 per loaf = $4.50\n",
            "\n",
            "**Step 5: Repeat steps 3-4 until the task is complete**\n",
            "\n",
            "Next, I will calculate the total cost including sales tax:\n",
            "\n",
            "Total cost without tax = $1.50 (apples) + $4.50 (bread) = $6.00\n",
            "Sales tax = 8% of $6.00 = $0.48\n",
            "Total cost with tax = $6.00 + $0.48 = $6.48\n",
            "\n",
            "**Step 6: Provide the final answer or solution**\n",
            "\n",
            "The total cost of the shopping trip is $6.48.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "ja7ZCUY2MJT2"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}